package com.xms.security.service;

import com.xms.security.entity.Privilege;
import com.xms.security.identity.ICurrentUser;
import com.xms.security.service.principal.ISystemUserPermissionService;
import com.xms.security.service.sitemap.IPrivilegeFinderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * <p>
 * PrivilegeFilterService
 * </p>
 *
 * @author migo
 * @since 2021/9/4
 */
@Service
public class PrivilegeFilterService implements IPrivilegeFilterService {
    private IPrivilegeFinderService _privilegeFinderService;
    private ISystemUserPermissionService _systemUserPermissionService;

    @Autowired
    public void PrivilegeFilterService(IPrivilegeFinderService privilegeFinderService,
                                       ISystemUserPermissionService systemUserPermissionService) {
        _privilegeFinderService = privilegeFinderService;
        _systemUserPermissionService = systemUserPermissionService;
    }

    @Override
    public boolean hasPermission(ICurrentUser currentUser, String areaName, String className, String methodName, boolean ignoreNull) {
        if (currentUser.isAdministrator()) {
            return true;
        }
        return validPermission(currentUser, _privilegeFinderService.getByName(areaName, className, methodName), ignoreNull);
    }

    @Override
    public boolean hasPermission(ICurrentUser currentUser, String url, boolean ignoreNull) {
        if (currentUser.isAdministrator()) {
            return true;
        }
        return validPermission(currentUser, _privilegeFinderService.getByUrl(url), ignoreNull);
    }

    private boolean validPermission(ICurrentUser currentUser, Privilege p, boolean ignoreNull) {
        if (ignoreNull && null == p) {
            return true;
        }
        if (!p.getAuthorizationenabled()) {
            return true;
        }
        Privilege up = _systemUserPermissionService.getAuthPrivilege(currentUser.getUser().SystemUserId, p.getUrl());
        if (up != null) {
            return true;
        }
        return false;
    }
}
